package com.example.springboot.controller.guava;


import com.example.springboot.config.anotation.requstlimit.Limit;
import com.google.common.util.concurrent.RateLimiter;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.concurrent.TimeUnit;

/**
 * @Author:ChenZhangKun
 * @Date: 2021/10/11 14:32
 */
@RestController
@RequestMapping("/guava/limit")
@Slf4j
public class LimitController {
    /**
     * 限流策略:1秒2个请求
     * Google开源工具包Guava提供了限流工具类RateLimiter，该类基于令牌桶算法实现流量限
     */
    private final RateLimiter limiter = RateLimiter.create(2.0);

    private DateTimeFormatter format = DateTimeFormatter.ofPattern("yyyy-MM-dd hh:mm:ss");

    @GetMapping("/get")
    public String testLimiter() {
        // 500毫秒没有拿到令牌，则进入服务降级
        boolean acquire = limiter.tryAcquire(500, TimeUnit.MICROSECONDS);
        if (!acquire) {
            log.warn("【进入服务降级，时间{}】", LocalDateTime.now().format(format));
            return "当前排队人数较多，请稍后再试！";
        }
        log.info("【获取令牌成功，时间{}】", LocalDateTime.now().format(format));
        return "请求成功";
    }

    @GetMapping("/get/aop")
    @Limit(key = "testLimiterAop",permitsPerSecond = 2.0,timeout = 500L,timeunit = TimeUnit.MICROSECONDS)
    public String testLimiterAop() {
        return "请求成功";
    }
}
